import sensor, image, time

#Base_threshold = (53, 33, -5, 43, 31, -9)  # 晚上底色阈值

Base_threshold = (59, 33, 12, 43, 27, -9) # 白天底色阈值

B_threshold = (5, 32, -17, 20, -6, 17)      # 黑色阈值
W_threshold = (53, 76, -36, 8, -12, 28) # 白色阈值

# 初始化摄像头
sensor.reset()
# 设置摄像头像素格式为RGB565（也可以设置为灰度但是颜色识别就无法使用了）
sensor.set_pixformat(sensor.RGB565)#RGB565   GRAYSCALE
# 设置摄像头像素大小为QVGA（320x240）
sensor.set_framesize(sensor.QVGA)
#设置摄像头的自动增益和自动白平衡为关闭
#sensor.set_auto_gain(False)
#sensor.set_auto_whitebal(False)

# 启动摄像头
sensor.skip_frames(time = 2000)
clock = time.clock()


# 变量初始化
first_identify = True #识别棋盘是否完成
corner_accum = [(0,0)] * 9 #存储小棋盘的中心坐标
count = 0  # 计数识别次数

sorted_points = [(0,0)] * 9 #存储小棋盘排序 以后的 中心坐标

vul_points = [0]* 9 #存储盘中的物体  白 1 黑 2  无 0

fine_sccess = 1


############################坐标排序函数##
def sort_points(points):#坐标排序函数
    # 按y坐标排序
    points = sorted(points, key=lambda p: p[1])
    # 将排序后的点分成三行，每行三个点
    rows = [points[i:i+3] for i in range(0, len(points), 3)]
    # 对每一行按x坐标排序
    sorted_points = [sorted(row, key=lambda p: p[0]) for row in rows]
    # 将排序后的点合并成一个列表
    sorted_points = [point for row in sorted_points for point in row]
    return sorted_points
############################坐标排序函数##END

print('test point--------------1-----主循环开始')
while(True):
    clock.tick()
    img = sensor.snapshot()
    img_re = img   #备用图像1
    img_re2 = img   #备用图像2

    while fine_sccess == 1:# 识别9个数
        print('test point--------------2-----寻找是否为9个')
        imgfind = sensor.snapshot()
        Base_blobs = imgfind.find_blobs([Base_threshold],roi=(10,10,300,220), pixels_threshold=800, area_threshold=800)
        find_count = 0

        for blob in Base_blobs:
            # 获取斑点的最小外接矩形的四个角
            corners = blob.min_corners()
            # 滤除棋盘边框：根据blob的位置和大小过滤
            if blob.w() > 100 and blob.h() > 100:  # 假设棋盘边框较大
                continue
            if blob.w() < 20 and blob.h() < 20:  # 假设小于就不用
                continue
            img.draw_cross(blob.cx(), blob.cy(), #在图像中画一个十字
                           size=2, color=(255, 0, 0))        #x,y是坐标 sizes是大小
            corner_accum[find_count]= (blob.cx(), blob.cy())

            for i in range(4):
                img.draw_line(corners[i][0], corners[i][1], corners[(i + 1) % 4][0], corners[(i + 1) % 4][1],color=(255, 0, 0))
            find_count += 1
            print('test point--------------2-----在一个图像中找到了%d 个' %find_count)
        if  find_count == 9:
            print('test point--------------2-----寻找的是9个图保存')

            print('test point--------------2-----处理任务 ' )

            print('test point--------------2-----结束寻找退出循环 ' )

            print('test point--------------3-----打印识别坐标' )
            print(corner_accum)

            print('test point--------------3-----打印转换完成的坐标' )
            sorted_points = sort_points(corner_accum)
            print(sorted_points)
            break
        else:
            print('test point--------------2-----没找到继续找' )
            corner_accum = [(0,0)] * 9 #坐标归零
            continue
    fine_sccess = 0

    print('test point--------------4-----在图上绘制出9个十字中心' )
    for i in range(9):
        img.draw_cross(sorted_points[i][0], sorted_points[i][1], #在图像中画一个十字
                       size=2, color=(255, 0, 255))        #x,y是坐标 sizes是大小
        img.draw_string(sorted_points[i][0], sorted_points[i][1], '%d' % (i+1), color=(255, 0, 255),scale = 2) #在图像中写字 8x10的像素
           #x,y是坐标。使用\n, \r, and \r\n会使光标移动到下一行。
           #text是要写的字符串
    print('test point--------------5-----在每一个小棋盘中识别棋子' )

    for i in range(9):
        _blobs = img_re.find_blobs([W_threshold,B_threshold],
                                    roi = (sorted_points[i][0]-35,sorted_points[i][1]-35,70,70),
                                    pixels_threshold=800, area_threshold=800)

        if _blobs == [] :#判断是否为空
            print('test point--------------6-----%d 为无'%(i+1))
#            print('%d wu' %(i+1))
            vul_points[i] = 0

        for blob in _blobs:
            # 滤除棋盘边框：根据blob的位置和大小过滤
            if blob.w() > 55 and blob.h() > 55:  # 假设棋盘边框较大
                continue
            if blob.w() < 20 and blob.h() < 20:  # 假设小于就不用
                continue
            # 进一步验证色块形状是否接近圆形（判断宽高比）
            aspect_ratio = blob.w() / blob.h()
            if aspect_ratio < 0.6 or aspect_ratio > 1.4:  # 假设棋子的宽高比接近1
                continue
            if blob.code() == 1:#白色
                # 绘制矩形框在白色块周围
                enclosing_circle = blob.enclosing_circle()
                img.draw_circle(enclosing_circle[0], enclosing_circle[1], enclosing_circle[2], color=(0, 255, 0))

                print('test point--------------6-----%d 为白'%(i+1))
#                print('%d +bai'%(i+1))
                vul_points[i] = 1
            elif blob.code() == 2:   #黑色
                enclosing_circle = blob.enclosing_circle()
                img.draw_circle(enclosing_circle[0], enclosing_circle[1], enclosing_circle[2], color=(0, 0, 255))
#                print('%d +hei'%(i+1))

                print('test point--------------6-----%d 为黑'%(i+1))
                vul_points[i] = 2
    print('test point--------------6-----打印数组')

    print(vul_points)

    print('test point--------------ENDMAIN-----帧率 %d '% clock.fps())
#    print(clock.fps())              # Note: OpenMV Cam runs about half as fast when connected
##                                    # to the IDE. The FPS should increase once disconnected.
